<div>
    <div  style="width:100%;text-align: right;background-color: #009E94;" >
        <input id="peiZhiCheNewJianKaiLiaoYuanAssessMonth" data-options="label:'考核月份',labelWidth:60,width:200" type= "text" class= "easyui-datebox" required ="required">
        <a id="newKaiLiaoYuanSubmit" class="easyui-linkbutton" style="width: 80px;background-color:#a1af1a" plain=true><i class="fa fa-check-circle fa-lg fa-fw"></i>提交</a>
    </div>
    <div>
        <!--奖金表格-->
        <table id="peiZhiCheJianNewKaiLiaoYuan"></table>
    </div>
    <div id="peiZhiCheJianNewKaiLiaoYuanToolbar" style="text-align: right;display: none">
        <div style="float: left">
            <a class="easyui-linkbutton" data-options="plain:true"><i class="fa fa-plus-square fa-fw" aria-hidden="true"></i>新增</a>
            <a class="easyui-linkbutton" data-options="plain:true">|</a>
            <a class="easyui-linkbutton" data-options="plain:true" onclick="javaScript:$('#peiZhiCheJianNewKaiLiaoYuan').edatagrid('destroyRow')"><i class="fa fa-trash fa-fw" aria-hidden="true"></i>删除</a>
        </div>
        <div style="float: right;padding-right:15px">
        <a class="easyui-linkbutton" data-options="plain:true" onclick="javaScript:$('#peiZhiCheJianNewKaiLiaoYuan').edatagrid('saveRow')"><i class="fa fa-floppy-o fa-fw" aria-hidden="true"></i>保存</a>
        </div>
        <div style="clear: both"></div>
    </div>
    <script th:inline="none">
        //当前编辑行的索引
        var peiZhiCheJianNewKaiLiaoYuanIndex = 0;
        //提交数据
        $("#newKaiLiaoYuanSubmit").click(function () {
            $.messager.confirm('确认对话框', '<span style="color: red">注意：提交会初始化当月(培训组长)的绩效考核数据,</span>您确定要提交吗？', function(r){
                if (r){
                    //获取考核数据：判断最终综合绩效是否有值
                    var rows = $("#peiZhiCheJianNewKaiLiaoYuan").datagrid("getRows");
                    // 1、封装年月和部门---全局变量设定在jxAssessGlobalVariable的js文件中；
                    rows.forEach(function (val) {
                        val.assessYear=pzcj_currentYear;
                        val.assessMonth=pzcj_currentMonth;
                        val.assessDept=pzcj_currentDept;
                    })
                    //获取页脚行的数据：合计：班级的
                    rows=JSON.stringify({maps:window.kailiaoyuanFooters,jxAssessPzcjs:rows})
                    // rows=JSON.stringify(rows)
                    //提交数据
                    var resultMessage = commonAjax("post","/jx/pzcj/addNewKaiLiaoYuanAssessData",rows,"application/json;charset=utf-8");
                    if (resultMessage.status==200){
                        //清空数据----footer：行尾
                        $("#peiZhiCheJianNewKaiLiaoYuan").datagrid("loadData", {total: 0, rows: [],footer:[]});
                        windowsOperation(null,null,resultMessage)
                    }else {
                        layer.msg(resultMessage.msg,{"icon":5})
                    }
                }
            });
        })

        var date= new Date();
        //选择月份加载月份数据
        $("#peiZhiCheNewJianKaiLiaoYuanAssessMonth").datebox({
            onSelect: function(date){
                $("#peiZhiCheJianNewKaiLiaoYuan").datagrid("loadData", {total: 0, rows: [],footer:[]});
                var currentYear=date.getFullYear()
                var currentMonth=date.getMonth()+1
                newkaiLiaoYuanInit(currentYear,currentMonth)
                addPZCJData("peiZhiCheJianNewKaiLiaoYuan",window.JX_PZCJ_NEWKAILIAOYUAN,"1002O110000000000MMB",currentYear,currentMonth)
            }

        })

        //进页面默认调用当月数据
        newkaiLiaoYuanInit(date.getFullYear(),date.getMonth()+1)

        //绩效考核表初始化方法
        function newkaiLiaoYuanInit(currentYear,currentMonth) {
            window.pzcj_currentYear = currentYear;//年
            window.pzcj_currentMonth = currentMonth; //月
            var currentYM=currentYear+"年"+currentMonth+"月";
            var kaiLiaoYuan = {
                init: [//表头
                    [
                        {
                            "title": ' <span style="font-size: 18px">新开料员综合绩效奖</span><span style="color: #009E94">(绩效奖金标准*0.8+第一次打板金额(B1）)*出勤率-绩效扣款(C1)</span>',
                            "align": "center",
                            "colspan": 13
                        },
                    ],
                    [
                        {"title": '考核部门（科室）:', "align": "center", "colspan": 3},
                        {"field": 'id3', "title": "生产部/配制车间", "align": "center", "colspan": 2},
                        {"title": '', "align": "center", "colspan": 4},
                        {"title": '考核周期:', "align": "center"},
                        {"field": 'id2', "title": currentYM, "align": "center","colspan":3},
                    ],
                    [
                        {"field": 'id', "title": 'ID', "width": 0, "align": "center", "hidden": "true"}
                        , {"field": 'empName', "title": '姓名', "width": 30, "align": "center"}
                        , {"field": 'empCode', "title": '工号', "width": 30, "align": "center"}
                        , {"field": 'postName', "title": '岗位', "width": 30, "align": "center"}
                        ,{"field": 'empGroup', "title": '班组', "width": 30, "align": "center"}
                        , {
                        "field": 'entryMonth', "title": '入职月份', "width": 30, "align": "center",
                        "editor": {
                            "type": "combobox",
                            "options": {
                                valueField: "entryMonth",
                                textField: "entryText",
                                panelHeight: "auto",
                                data: [{entryMonth: "1", entryText: "入职一个月"}, {
                                    entryMonth: "2",
                                    entryText: "入职二个月"
                                }, {entryMonth: "3", entryText: "入职三个月"},]
                            },
                        },
                        formatter: function (value, row, index) {
                            switch (value) {
                                case "1":
                                    return "入职一个月";
                                    break;
                                case "2":
                                    return "入职二个月";
                                    break;
                                case "3":
                                    return "入职三个月";
                                    break;
                            }
                        }
                    }
                        , {
                        "field": 'productivity',
                        "title": '个人生产<br/>效率(%)',
                        "width": 30,
                        "align": "center",
                        "editor": {
                            "type": "textbox",
                            "options": {"precision": 2, "onChange": peiZhiCheJianNewKaiLiaoYuanProductivity}
                        }
                    }
                        , {
                        "field": 'performanceBonus',
                        "title": '绩效奖金<br/>标准（A1)',
                        "width": 30,
                        "align": "center",
                        "editor": {"type": "textbox", "options": {"readonly": true}}
                    }
                        , {
                        "field": 'dabanSuccess',
                        "title": '一次打板<br/>成功率(%)',
                        "width": 30,
                        "align": "center",
                        "editor": {"type": "textbox", "options": {"onChange": peiZhiCheJianNewKaiLiaoYuanDabanSuccess}}
                    }
                        , {
                        "field": 'dabanMoney',
                        "title": '第一次打板<br/>金额(B1）',
                        "width": 30,
                        "align": "center",
                        "editor": {"type": "textbox", "options": {"readonly": true}}
                    }
                        , {
                        "field": 'deduct',
                        "title": '绩效扣款(C1)',
                        "width": 30,
                        "align": "center",
                        "editor": {
                            "type": "textbox",
                            "options": {"onChange": peiZhiCheJianNewKaiLiaoYuanAttendanceRateAndDeduct}
                        }
                    }
                        , {
                        "field": 'attendanceRate',
                        "title": '出勤率(%)',
                        "width": 30,
                        "align": "center",
                        "editor": {
                            "type": "textbox",
                            "options": {"onChange": peiZhiCheJianNewKaiLiaoYuanAttendanceRateAndDeduct}
                        }
                    }
                        , {
                        "field": 'resultMoney',
                        "title": '最终综合<br/>绩效（元）',
                        "width": 30,
                        "align": "center",
                        "editor": {"type": "textbox", "options": {"readonly": true}}
                    }
                    ]]

            }
            //奖金基数表格
            $("#peiZhiCheJianNewKaiLiaoYuan").edatagrid({
                nowrap: false,
                columns: kaiLiaoYuan.init,
                showFooter: true,
                autoSave: true,
                fitColumns: true,
                scrollbarSize: 0,  //最右侧多出来的去除
                toolbar: "#peiZhiCheJianNewKaiLiaoYuanToolbar",
                onBeforeEdit: function (index, row) { //编辑器打开触发事件
                    peiZhiCheJianNewKaiLiaoYuanIndex = index;//保存当前索引
                },
                onAfterEdit:function (index, row) {
                    // console.log("在用户完成编辑一行的时候触发:统计最终综合绩效")
                    totalPeiZhiCheJianKaiLiaoYuan();
                },
                onDestroy:function (index,row) { //删除一行触发事件
                    totalPeiZhiCheJianKaiLiaoYuan();
                }

            })
        }

        //合计最终综合绩效
        function totalPeiZhiCheJianKaiLiaoYuan() {
            console.log("合计最终综合绩效")
            var rows = $("#peiZhiCheJianNewKaiLiaoYuan").datagrid("getRows");
            //合计最终综合绩效
            var  result=0;
            //封装统计每个班组的班组名、班组人的个数、班组的总绩效奖金
            var arrays=[];          //[{"name": "A","total": 5,"totalValue": 150.36}, {"name": "B","total": 3,"totalValue": 150}]
            rows.forEach(function (row) {
                var val=Number(row.resultMoney)
                if (val){
                    result+=val
                }
                //统计有多少种类型
                totalJxType(arrays,row);

            })
            //console.log("统计有多少种类型",arrays)
            window.kailiaoyuanFooters=[{empCode: "合计", resultMoney: fomatFloat(result,2)}]

            arrays.forEach(function (value) {
                var ar={};
                ar.empCode=value.name+"组平均绩效奖金";
                ar.total=value.total;
                ar.groupTotalBonus=fomatFloat(value.totalValue,2);
                ar.resultMoney=fomatFloat(Number(value.totalValue)/Number(value.total),2)
                window.kailiaoyuanFooters.push(ar)  //封装行尾中
            })

            //添加页脚行方法
            $("#peiZhiCheJianNewKaiLiaoYuan").edatagrid('reloadFooter', window.kailiaoyuanFooters)

        }

        //统计封装班组、班组总奖金、班组人数
        function totalJxType(b,row) {
            var empGroup=row.empGroup;      //班组
            var result={};             // {"name": "A","totalNum": 5,"totalValue": 150.36},
            let temp=1;
            // [{"name": "A","total": 5,"avg": 150.36}, {"name": "B","total": 3,"totalValue": 150.36}]
            if (b.length>0){
                b.forEach(function (val) {
                    //判断empGroup在不在这个数组中，若在临时值改为0
                    if (empGroup && empGroup != "" && val.name == empGroup){
                        temp=0;
                        //第二次以上：处理对象result
                        val.total+=1;
                        val.totalValue= Number(val.totalValue)+Number(row.resultMoney);
                    }
                })
            }

            //第一次添加到数组中
            if (temp){
                result.name=empGroup;     // 班组
                result.total=1;     //个数
                result.totalValue=row.resultMoney;  //个人最终绩效奖金
                b.push(result);
            }
        }

        //个人生产效率触发事件:计算绩效奖金标准
        function peiZhiCheJianNewKaiLiaoYuanProductivity(newValue,oldValue) {
            if (newValue) {
                newValue = Number(newValue)
                var ed = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianNewKaiLiaoYuanIndex,
                    field: 'performanceBonus'
                }); //绩效奖金标准编辑器对象
                var performanceBonusJ = ed.target;  // 绩效奖金标准jquery对象
                var performanceBonus;
                //1、x ≤ 97% 或 x ≥ 105%=0；2、97% < x ≤ 99%或者103% ≤ x  < 105%=400；
                // 3、100% < x < 103%或者99% < x < 100%=500；4、x=100%=600
                //入职问题：入职一个月、二个月、三个月：不同的考核指标
                var entryMonth = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianNewKaiLiaoYuanIndex,
                    field: 'entryMonth'
                }).target.combobox("getValue");
                var n,n1,n2,n3,n4;
                switch (entryMonth) {
                    case "1":
                        n=70;n1=105;n2=75;n3=80;n4=105;
                        break;
                    case "2":
                        n=80;n1=105;n2=85;n3=90;n4=105;
                        break;
                    case "3":
                        n=90;n1=105;n2=95;n3=100;n4=105;
                        break;
                }
                if (newValue <= n || newValue >= n1) {
                    performanceBonus=0;
                } else if (n <= newValue && newValue < n2) {
                    performanceBonus=200
                } else if (n2 <= newValue && newValue < n3) {
                    performanceBonus=300
                } else if (n3 <= newValue && newValue <= n4) {
                    performanceBonus=400
                } else {
                    var productivity= getEditObject("productivity") //个人生产
                    productivity.textbox("setValue", "")
                    layer.msg("请输入正确的值！")
                    return
                }
                performanceBonusJ.textbox("setValue",performanceBonus)

                //为0的时候触发一下打板成功率，为0，防止用户在填完整行后，又去修改
                //获取值打板成功率值，
                var dabanSuccess = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianNewKaiLiaoYuanIndex,
                    field: 'dabanSuccess'
                }).target.textbox("getValue");
                //调用一次打板成功率触发事件方法
                peiZhiCheJianNewKaiLiaoYuanDabanSuccess(dabanSuccess)
                peiZhiCheJianNewKaiLiaoYuanresultMoney() //计算最终绩效的方法
            }
        }

        //一次打板成功率触发事件:计算 第一次打板金额(B1）
        function peiZhiCheJianNewKaiLiaoYuanDabanSuccess(newValue,oldValue) {
            if (newValue) {
                newValue = Number(newValue)
                //console.log("一次打板成功率触发事件")
                var ed = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianNewKaiLiaoYuanIndex,
                    field: 'dabanMoney'
                }); //第一次打板金额(B1）编辑器对象
                var dabanMoneyJ = ed.target;  // 绩效奖金标准jquery对象
                //B1奖金获取方式：有两步
                //第一步 先获取一次打板通过率 (Y) 的:获取方式3种条件
                var y;   //一次打板通过率
                if (newValue >= 70) { // 1、Y >=75%按100%；
                    y = 1
                } else if (50 <= newValue && newValue < 70) {//2、50%≤ Y < 70%，占比例计算：如56%，则56%除以70%的公式；
                    y = newValue / 70;
                } else if (newValue > 50) {//3、Y >50%,Y=0%
                    y = 0
                } else {
                    var dabanSuccess= getEditObject("dabanSuccess")
                    dabanSuccess.textbox("setValue", "")
                    layer.msg("请输入正确的值")
                    return
                }
                //第二步然后通过公式：A1*一次打板通过率(Y)*0.2计算出最终的B1奖金
                var performanceBonusJ = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianNewKaiLiaoYuanIndex,
                    field: 'performanceBonus'
                }).target; //绩效奖金标准编辑器对象
                var performanceBonus = performanceBonusJ.textbox("getValue");
                if (performanceBonus) {
                    var dabanMoney=fomatFloat(Number(performanceBonus) * y * 0.2, 2)
                    dabanMoneyJ.textbox("setValue",dabanMoney)
                } else {
                    //清空一次打板成功率用户输入的值
                    var dabanSuccess= getEditObject("dabanSuccess")
                    dabanSuccess.textbox("setValue", "")
                    layer.msg("请先计算出绩效奖金标准的值")
                }

                peiZhiCheJianNewKaiLiaoYuanresultMoney() //计算最终绩效的方法
            }

        }

        //扣款绩效和出勤率触发事件
        function peiZhiCheJianNewKaiLiaoYuanAttendanceRateAndDeduct() {
            peiZhiCheJianNewKaiLiaoYuanresultMoney() //计算最终绩效的方法
        }

        //计算最终绩效的方法:(计算绩效奖金标准*0.8+第一次打板金额(B1）)*出勤率-绩效扣款(C1)
        function peiZhiCheJianNewKaiLiaoYuanresultMoney() {
            //为了以后有可能会更改字段的位置或添加问题，不使用获取编辑器对象数组的方法
            //console.log("计算最终绩效的方法")
            //绩效奖金标准
            var performanceBonus = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: 'performanceBonus'
            }).target.textbox("getValue");

            //第一次打板金额
            var dabanMoney = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: 'dabanMoney'
            }).target.textbox("getValue");

            //出勤率
            var attendanceRate = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: 'attendanceRate'
            }).target.textbox("getValue");

            //绩效扣款
            var deduct = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: 'deduct'
            }).target.textbox("getValue");

            // 获取最终绩效奖金编辑器对象
            var resultMoney = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: 'resultMoney'
            }).target;
            var result;
            result= fomatFloat((Number(performanceBonus)*0.8+Number(dabanMoney))*Number(attendanceRate)/100,2)-Number(deduct);
            if (result){
                resultMoney.textbox("setValue",result);
                //保存编辑
                // $('#peiZhiCheJianKaiLiaoYuan').edatagrid("saveRow")
            }

        }

        //保留小数点方法：四舍五入，不保留尾数0,参数一：值，参数二：要保留的小数点
        function fomatFloat(src, pos) {
            return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
        }

        //获取当前编辑行指定的jquery对象
        function getEditObject(fieldValue) {
            var j = $('#peiZhiCheJianNewKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianNewKaiLiaoYuanIndex,
                field: fieldValue
            }).target; //第一次打板成功率编辑器对象
            return j
        }
    </script>
</div>

